jetcrab\lexer\tokens/
literals.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4pub enum Literal {
5    Number(f64),
6    BigInt(String),
7    String(String),
8    TemplateString(String),
9    Boolean(bool),
10    Null,
11    Undefined,
12    Regex(String),
13}
14
15impl Literal {
16    pub fn as_number(&self) -> Option<f64> {
17        match self {
18            Literal::Number(n) => Some(*n),
19            _ => None,
20        }
21    }
22
23    pub fn as_string(&self) -> Option<&str> {
24        match self {
25            Literal::String(s) => Some(s),
26            Literal::TemplateString(s) => Some(s),
27            _ => None,
28        }
29    }
30
31    pub fn as_boolean(&self) -> Option<bool> {
32        match self {
33            Literal::Boolean(b) => Some(*b),
34            _ => None,
35        }
36    }
37
38    pub fn is_null(&self) -> bool {
39        matches!(self, Literal::Null)
40    }
41
42    pub fn is_undefined(&self) -> bool {
43        matches!(self, Literal::Undefined)
44    }
45
46    pub fn is_falsy(&self) -> bool {
47        match self {
48            Literal::Boolean(false) => true,
49            Literal::Null => true,
50            Literal::Undefined => true,
51            Literal::Number(n) => *n == 0.0,
52            Literal::String(s) => s.is_empty(),
53            _ => false,
54        }
55    }
56
57    pub fn is_truthy(&self) -> bool {
58        !self.is_falsy()
59    }
60}